package akaram.util.dice;

/**
 * 
 * This class represent a dice roll definition
 * 
 * @author japaz
 *
 */
public class DiceThrow {
	
	private int number;
	private int faces;
	private int plus;
	
	public DiceThrow(int number, int faces, int plus)
	{
		this.number = number;
		this.faces = faces;
		this.plus = plus;
	}
	
	private int parseFaces(String faces)
	{
		if ( faces.equals("%"))
			return 100;
		else
			return Integer.parseInt(faces);
	}
	
	private int parseNumber(String number)
	{
		if ( number.equals(""))
			return 1;
		else
			return Integer.parseInt(number);
	}
	
	/**
	 * 
	 * Dice throw definition the syntax: NdF+P or P+NdF or NdF-P
	 * 
	 * @param dice
	 * @return
	 * @throws RollDiceException 
	 */
	public DiceThrow(String throwDefinition) throws RollDiceException
	{
		// Supressing spaces
		throwDefinition = throwDefinition.replaceAll(" ", "");
		
		String[] pp = throwDefinition.split("[dD]");
		
		if ( pp.length != 2 )
			throw new RollDiceException("No 'd' in the roll expression.");
		
		String[] pp0 = pp[0].split("[+-]");
		
		if ( pp0.length == 2 )
		{
			this.plus = Integer.parseInt(pp0[0]);
			this.number = parseNumber(pp0[1]);
			this.faces = parseFaces(pp[1]);
		}
		else
		{
			String[] pp1 = pp[1].split("[+-]");
			
			if ( pp1.length == 2 )
			{
				this.number = parseNumber(pp[0]);
				this.faces = parseFaces(pp1[0]);
				this.plus = Integer.parseInt(pp1[1]);
			}
			else
			{
				this.number = parseNumber(pp[0]);
				this.faces = parseFaces(pp[1]);
			}
		}
	}
	
	public int getNumber() {
		return number;
	}

	public int getFaces() {
		return faces;
	}

	public int getPlus() {
		return plus;
	}
	
	public int getThrow()
	{
		return DiceRoller.rollDice(this);
	}

	public String toString()
	{
		StringBuffer sb = new StringBuffer();
		
		sb.append(number).append("d").append(faces);
		if ( plus!= 0 )
		{
			sb.append("+").append(plus);
		}
		
		return sb.toString();
	}
	
	public static void main(String[] params)
	{
		  try {
			    DiceThrow d = new DiceThrow("d%%+10");
			    System.out.print(d);
			  } catch (RollDiceException e) {
			}
	}

}
